package cn.com.oceansoft.oauth.server.biz.service.impl;

import cn.com.oceansoft.oauth.server.biz.dao.IOAuthClientsDao;
import cn.com.oceansoft.oauth.server.biz.entity.OAuthClients;
import cn.com.oceansoft.oauth.server.biz.service.IOAuthClientsService;
import cn.com.oceansoft.oauth.server.domain.dto.OauthClientDetailsDto;
import cn.com.oceansoft.oauth.server.domain.oauth.OauthClientDetails;
import cn.com.oceansoft.oauth.server.domain.oauth.OauthRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by BEN on 2016/4/19.
 */
@Service
public class OAuthClientsServiceImpl implements IOAuthClientsService {

    @Autowired
    private IOAuthClientsDao dao;

    @Autowired
    private OauthRepository oauthRepository;

    @Override
    public OAuthClients loadOauthClients(String clientId) {
        return dao.findOAuthClients(clientId);
    }

    @Override
    public List<OAuthClients> loadAllOauthClients() {
        return dao.findAllOauthClients();
    }


    @Override
    public List<OAuthClients> loadLikeOauthClients(String clientId) {
        return dao.findLikeOauthClients(clientId);
    }

    @Override
    public void archiveOauthClients(String clientId) {
        //dao.updateOAuthClientsArchive(clientId, true);
        oauthRepository.updateOauthClientDetailsArchive(clientId, true);
    }

    public void unArchiveOauthClients(String clientId) {
        //dao.updateOAuthClientsArchive(clientId, false);
        oauthRepository.updateOauthClientDetailsArchive(clientId, false);
    }

    @Override
    public void registerClients(OAuthClients oAuthClients) {

        dao.saveOAuthClients(oAuthClients);

        OauthClientDetails clientDetails = new OauthClientDetails();
        clientDetails.clientId(oAuthClients.getClientId());
        clientDetails.clientSecret(oAuthClients.getClientSecret());
        clientDetails.authorizedGrantTypes("client_credentials");
        clientDetails.scope("read");
        clientDetails.archived(true);
        clientDetails.trusted(true);
        oauthRepository.saveOauthClientDetails(clientDetails);
    }
}
